import { reactive, computed, ref, watch } from 'vue'
import { defineStore } from 'pinia';
import type { SessionItem } from '@/services/type';
import { api } from '@/services/api';

import cloneDeep from 'lodash/cloneDeep';

export const userSessionStore = defineStore('session', () => {

    // 当前会话参数
    const currentSession = reactive<{session_id: number, isLoading: Boolean}>({session_id: 1, isLoading: false});
    // 是否加载数据
    const isLoading = ref(false);
    // 是否最后一页
    const isLast = ref(false);
    // 游标值
    const cursor = ref('');
    // 会话列表
    let sessionList = reactive<SessionItem[]>([]);
    // 当前会话信息
    const currentSessionInfo = computed(() => sessionList.find(session => session.session_id == currentSession.session_id));

    watch(currentSession, async (data) => {
        const session = sessionList.find(session => session.session_id == currentSession.session_id);
        if(session && session.unread_count > 0) {
            // 清空当前消息未读数
            await api.chat.clearUnread({ sessionId: data.session_id });
            // 消息未读数设置为0
            session.unread_count = 0;
        }
    });

    // 初始化参数
    const initParam = () => {
        sessionList.length = 0;
        isLoading.value = false;
        isLast.value = false;
        cursor.value = '';
    }

    // 获取会话列表
    const getSessionList = async () => {
        sessionList.length = 0;
        // 查询聊天会话列表
        const response = await api.chat.querySessionList({
            size: 20,
            cursor: cursor.value,
            receive_uid: ""
        });
        if(response.code == 0) {
            sessionList.push(...response.data.list);
            // 是否最后一页
            isLast.value = response.data.isLast;
            // 游标值
            cursor.value = response.data.cursor; 
        }
    }

    // 更新会话信息时间
    const updateSessionLastActiveTime = (session_id: number, session?: SessionItem) => {
        const currentSession = sessionList.find((item) => item.session_id === session_id)
        if (currentSession) {
            Object.assign(currentSession, { active_time: Date.now() });
        } else if(session) {
            const newItem = cloneDeep(session)
            newItem.active_time = Date.now()
            sessionList.unshift(newItem)
        }
        sortAndUniqueSessionList();
    }

    // 会话列表去重并排序
    const sortAndUniqueSessionList = () => {
        const temp: Record<string, SessionItem> = {}
        sessionList.forEach((item) => (temp[item.session_id] = item))
        sessionList.splice(0, sessionList.length, ...Object.values(temp))
        sessionList.sort((pre, cur) => cur.active_time - pre.active_time)
    }

    return { 
        isLoading, 
        currentSession, 
        currentSessionInfo, 
        sessionList, 
        initParam, 
        getSessionList, 
        updateSessionLastActiveTime 
    }
});